package com.xtpt.disaster.controller;

import com.alibaba.fastjson.JSON;
import com.xtpt.disaster.bean.ClientCmdExecResult;
import com.xtpt.disaster.bean.JobDetail;
import com.xtpt.disaster.common.PortalResult;
import com.xtpt.disaster.common.consts.StatusConst;
import com.xtpt.disaster.service.JobDetailService;
import com.xtpt.disaster.utils.LogUtil;
import com.xtpt.disaster.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Paths;

/**
 * @author jack_xin
 * @ClassName CallbackResultController
 * @Desc TODO
 * @date 2021年12月29日 11:16
 * @Version TODO
 */
/**
 * @author jack_xin
 * @ClassName CallbackResultController
 * @Desc 回调结果处理器
 * @date 2021年12月24日 14:18
 * @Version TODO
 */
@RestController
@RequestMapping(value = "/result")
public class CallbackResultController {
    @Autowired
    JobDetailService jobDetailService;
    /**
     * @Description: 接收代理客户端任务执行结果
     * @Author: jack_xin
     * @Date: 2021/12/27 下午 3:13
     * @param jobId: 结果所属作业ID
     * @param resultStr: 结果字符串本身
     * @return: com.xtpt.disaster.common.PortalResult
     **/
    @RequestMapping("/receiver/{jobId}")
    public PortalResult receiver(@PathVariable("jobId") Long jobId, @RequestBody String resultStr)
    {
        if(jobId!=null && !StringUtils.isEmpty(resultStr))
        {
            JobDetail jobDetail=jobDetailService.getById(jobId);
            if(jobDetail==null)
            {
                LogUtil.logger.error("jobId:"+jobId+" 不存在！");
                return PortalResult.error(jobId+" 不存在！");
            }
            try {
                ClientCmdExecResult result= JSON.parseObject(resultStr,ClientCmdExecResult.class);
                jobDetail.setJobResult(JSON.toJSONString(result.getExecCmdResult()));
                jobDetail.setJobEndTime(TimeUtil.dateMaker());
                if(!result.isStatus())
                {
                    LogUtil.logger.error(JSON.toJSONString(result.getErrorCmdList()));
                }
                String serverFilesPath = jobDetail.getServerPath();
                boolean transOK=true;
                if(serverFilesPath!=null)
                {
                    for (String file:serverFilesPath.split(",")) {
                        transOK=cn.hutool.core.io.file.PathUtil.exists(Paths.get(file),true);
                        if(!transOK)
                        {
                            LogUtil.logger.error("文件："+file+"，未传输到服务器！");
                            break;
                        }
                    }
                }
                if(transOK)
                {
                    jobDetail.setJobStatus(StatusConst.SUCCESS);
                }
                else
                {
                    jobDetail.setJobStatus(StatusConst.ERROR);
                }
            }
            catch (Exception ex){
                jobDetail.setJobStatus(StatusConst.ERROR);
                jobDetail.setJobResult(jobDetail.getJobResult()+"\r\nException:"+ex.getMessage());
                LogUtil.logger.error(ex.getMessage());
                ex.printStackTrace();
            }
            Integer update= jobDetailService.updateByPrimaryKeySelective(jobDetail);
            LogUtil.logger.info("更新"+update+"条数据记录！");
            if(jobDetail.getJobStatus().equals(StatusConst.SUCCESS))
            {
                return PortalResult.ok("成功更新"+update+"条数据记录！");
            }
            else if(jobDetail.getJobStatus().equals(StatusConst.ERROR))
            {
                return PortalResult.ok("失败！"+jobDetail.getJobResult());
            }else
            {
                return PortalResult.ok("RUNNING");
            }
        }
        LogUtil.logger.error("结果上报参数不完整！\njobId:"+jobId+"\nresult:"+resultStr);
        return PortalResult.error("结果上报参数不完整！");
    }
}
